/**
 * JWT 工具
 */

const TOKEN_KEY = 'token'

export function saveToken(token) {
  localStorage.setItem(TOKEN_KEY, token)
}

export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

export function removeToken() {
  localStorage.removeItem(TOKEN_KEY)
}

export function getPayload(token) {
  const payload = token?.split('.')[1] ?? ''
  if (payload) {
    const { loginUser } = JSON.parse(atob(payload))
    const id = loginUser?.id
    const username = loginUser?.username
    const role = ['', 'superAdmin', 'admin', 'user'][loginUser?.role]
    return { id, username, role }
  }
}
